<template>
  <div class="inter-container">
    <!-- 头部搜索区域 -->
    <div class="header">
      <div class="back-button">
        <el-icon><arrow-left /></el-icon>
      </div>
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="最近过得好吗"
          class="input-with-select"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch" :loading="isLoading">搜索</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 提示信息 -->
    <div class="notice-bar">
      <el-alert
        title="此为深度AI生成内容，禁止利用其从事违法活动，请谨慎使用！"
        type="warning"
        :closable="true"
        show-icon
      />
    </div>

    <!-- 回复风格选择 -->
    <div class="style-section">
      <div class="style-title">
        当前回复风格：
        <el-tag size="small" effect="plain">{{ getCurrentStyleLabel() }}</el-tag>
      </div>
      <div class="style-options">
        <div
          v-for="style in replyStyles"
          :key="style.key"
          class="style-item"
          :class="{ active: selectedStyle === style.key }"
          @click="selectedStyle = style.key"
        >
          <span class="emoji">{{ style.emoji }}</span>
          <span class="label">{{ style.label }}</span>
        </div>
      </div>
    </div>

    <!-- 角色信息选择 -->
    <div class="role-selection">
      <div class="role-item">
        <el-dropdown @command="handleMyInfoSelect" trigger="click">
          <el-button type="primary" plain>
            <el-icon><user /></el-icon>
            {{ getCurrentMyInfo() }}
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="info in myInfoList" 
                :key="info.name" 
                :command="info"
              >
                <el-icon><user /></el-icon>
                {{ info.name }}
                <el-tag size="small" type="info" class="gender-tag">
                  {{ info.gender === 'male' ? '男' : '女' }}
                </el-tag>
              </el-dropdown-item>
              <el-dropdown-item divided command="view">
                <el-icon><view /></el-icon> 查看信息
              </el-dropdown-item>
              <el-dropdown-item command="add">
                <el-icon><plus /></el-icon> 新增信息
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div class="role-item">
        <el-dropdown @command="handleTargetInfoSelect" trigger="click">
          <el-button type="primary" plain>
            <el-icon><user-filled /></el-icon>
            {{ getCurrentTargetInfo() }}
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="info in targetInfoList" 
                :key="info.name" 
                :command="info"
              >
                <el-icon><user /></el-icon>
                {{ info.name }}
                <el-tag size="small" type="info" class="gender-tag">
                  {{ info.gender === 'male' ? '男' : '女' }}
                </el-tag>
              </el-dropdown-item>
              <el-dropdown-item divided command="view">
                <el-icon><view /></el-icon> 查看信息
              </el-dropdown-item>
              <el-dropdown-item command="add">
                <el-icon><plus /></el-icon> 新增信息
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="searchResults.length || isLoading">
      <div class="results-header">
        <div class="results-title">搜索结果：</div>
        <div class="response-time" v-if="responseTime">
          响应时间：{{ responseTime }}ms
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="isLoading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <!-- 结果列表 -->
      <div v-else class="results-list">
        <div v-for="(result, index) in searchResults" 
          :key="index" 
          class="result-item"
        >
          <div class="result-content">{{ result.content }}</div>
          <el-button 
            type="primary" 
            size="small" 
            text
            @click="copyContent(result.content)"
          >
            <el-icon><document-copy /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 新增信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'my' ? '新增我的信息' : '新增对方信息'"
      width="30%"
      class="custom-dialog"
    >
      <el-form :model="newInfo" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="newInfo.name" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="newInfo.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            v-model="newInfo.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddInfo">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看信息对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      :title="viewDialogType === 'my' ? '我的信息' : '对方信息'"
      width="30%"
      class="custom-dialog"
    >
      <template #header="{ close, titleId, titleClass }">
        <div class="dialog-header">
          <h4 :id="titleId" :class="titleClass">
            {{ viewDialogType === 'my' ? '我的信息' : '对方信息' }}
          </h4>
          <div class="dialog-actions">
            <el-button
              type="primary"
              link
              @click="handleEdit"
              v-if="!isEditing"
            >
              <el-icon><edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete"
              v-if="!isEditing"
            >
              <el-icon><delete /></el-icon>
              删除
            </el-button>
            <el-button @click="close">
              <el-icon><close /></el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <!-- 查看模式 -->
      <div class="info-view" v-if="!isEditing">
        <div class="info-item">
          <span class="label">名称：</span>
          <span class="value">{{ viewInfo.name }}</span>
        </div>
        <div class="info-item">
          <span class="label">性别：</span>
          <span class="value">{{ viewInfo.gender === 'male' ? '男' : '女' }}</span>
        </div>
        <div class="info-item">
          <span class="label">简介：</span>
          <span class="value">{{ viewInfo.description }}</span>
        </div>
      </div>

      <!-- 编辑模式 -->
      <el-form 
        v-else 
        :model="editInfo" 
        label-width="80px"
        class="edit-form"
      >
        <el-form-item label="名称">
          <el-input v-model="editInfo.name" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editInfo.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            v-model="editInfo.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer v-if="isEditing">
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveEdit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Cookies from 'js-cookie'
import OpenAI from 'openai'
import {
  User,
  UserFilled,
  ArrowDown,
  ArrowLeft,
  Plus,
  DocumentCopy,
  View,
  Edit,
  Delete,
  Close
} from '@element-plus/icons-vue'

// 状态定义
const searchText = ref('')
const selectedStyle = ref('')
const dialogVisible = ref(false)
const dialogType = ref('my')
const myInfoList = ref([])
const targetInfoList = ref([])
const searchResults = ref([])
const isLoading = ref(false)
const responseTime = ref(0)
const newInfo = ref({
  name: '',
  gender: 'male',
  description: ''
})
const viewDialogVisible = ref(false)
const viewDialogType = ref('my')
const viewInfo = ref({
  name: '',
  gender: 'male',
  description: ''
})
const isEditing = ref(false)
const editInfo = ref({
  name: '',
  gender: 'male',
  description: ''
})

// 回复风格配置
const replyStyles = [
  { key: 'cute', label: '可爱风', emoji: '😊', prompt: '以可爱活泼的语气回复' },
  { key: 'warm', label: '温柔体贴', emoji: '😌', prompt: '以温柔体贴的语气回复' },
  { key: 'sweet', label: '暖昧关系', emoji: '🥰', prompt: '以暧昧的语气回复' },
  { key: 'funny', label: '风趣幽默', emoji: '😆', prompt: '以幽默风趣的语气回复' },
  { key: 'topic', label: '找话题', emoji: '🤔', prompt: '帮助找寻合适的话题' },
  { key: 'flirt', label: '撒娇认错', emoji: '😳', prompt: '以撒娇的语气道歉认错' },
  { key: 'normal', label: '正常聊天', emoji: '💬', prompt: '以自然平和的语气进行日常对话' },
  { key: 'change', label: '转换话题', emoji: '🔄', prompt: '巧妙地将当前话题转向新的有趣话题' }
]

// OpenAI 客户端配置
const openai = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: import.meta.env.VITE_APP_DEEPSEEK_API_KEY,
  dangerouslyAllowBrowser: true
})

// 获取当前风格标签
const getCurrentStyleLabel = () => {
  const style = replyStyles.find(s => s.key === selectedStyle.value)
  return style ? style.label : '找话题'
}

// 获取当前选择的信息名称
const getCurrentMyInfo = () => {
  const myInfo = Cookies.get('myInfo')
  return myInfo ? JSON.parse(myInfo).name : '选择我的信息'
}

const getCurrentTargetInfo = () => {
  const targetInfo = Cookies.get('targetInfo')
  return targetInfo ? JSON.parse(targetInfo).name : '选择对方信息'
}

// 方法定义
const handleSearch = async () => {
  if (!searchText.value) {
    ElMessage.warning('请输入搜索内容')
    return
  }

  isLoading.value = true
  const startTime = Date.now()
  
  try {
    console.log('开始搜索')
    const currentStyle = replyStyles.find(style => style.key === selectedStyle.value)
    const myInfo = Cookies.get('myInfo') ? JSON.parse(Cookies.get('myInfo')) : null
    const targetInfo = Cookies.get('targetInfo') ? JSON.parse(Cookies.get('targetInfo')) : null

    let prompt = `请根据以下条件生成回复建议，并以JSON格式返回结果：\n`
    if (myInfo) {
      prompt += `我的信息：${myInfo.description}\n`
    }
    if (targetInfo) {
      prompt += `对方信息：${targetInfo.description}\n`
    }
    prompt += `回复风格：${currentStyle?.prompt || '普通对话'}\n`
    prompt += `搜索内容：${searchText.value}\n`
    prompt += `请返回JSON格式，包含多个可能的回复内容，格式如下：
    {
      "replies": [
        {"content": "回复内容1"},
        {"content": "回复内容2"}
      ]
    }`

    console.log('prompt:', prompt)
    const completion = await openai.chat.completions.create({
      messages: [
        { 
          role: "system", 
          content: "You are a helpful assistant that provides responses in JSON format." 
        },
        { 
          role: "user", 
          content: prompt 
        }
      ],
      model: "deepseek-chat",
      response_format: { type: "json_object" }
    })

    const result = JSON.parse(completion.choices[0].message.content)
    searchResults.value = result.replies
  } catch (error) {
    ElMessage.error('搜索失败，请稍后重试')
    console.error('Search error:', error)
  } finally {
    responseTime.value = Date.now() - startTime
    isLoading.value = false
  }
}

const handleViewInfo = (type) => {
  viewDialogType.value = type
  const info = type === 'my' ? 
    Cookies.get('myInfo') : 
    Cookies.get('targetInfo')
  
  if (info) {
    viewInfo.value = JSON.parse(info)
    viewDialogVisible.value = true
  } else {
    ElMessage.warning(`暂无${type === 'my' ? '我的' : '对方'}信息`)
  }
}

const handleMyInfoSelect = (command) => {
  if (command === 'add') {
    dialogType.value = 'my'
    dialogVisible.value = true
  } else if (command === 'view') {
    handleViewInfo('my')
  } else {
    Cookies.set('myInfo', JSON.stringify(command))
    ElMessage.success('已选择我的信息')
  }
}

const handleTargetInfoSelect = (command) => {
  if (command === 'add') {
    dialogType.value = 'target'
    dialogVisible.value = true
  } else if (command === 'view') {
    handleViewInfo('target')
  } else {
    Cookies.set('targetInfo', JSON.stringify(command))
    ElMessage.success('已选择对方信息')
  }
}

const handleAddInfo = () => {
  if (!newInfo.value.name || !newInfo.value.description) {
    ElMessage.warning('请填写完整信息')
    return
  }

  const info = {
    name: newInfo.value.name,
    gender: newInfo.value.gender,
    description: newInfo.value.description
  }

  if (dialogType.value === 'my') {
    myInfoList.value.push(info)
    Cookies.set('myInfoList', JSON.stringify(myInfoList.value))
  } else {
    targetInfoList.value.push(info)
    Cookies.set('targetInfoList', JSON.stringify(targetInfoList.value))
  }

  dialogVisible.value = false
  newInfo.value = { name: '', gender: 'male', description: '' }
  ElMessage.success('添加成功')
}

const copyContent = (content) => {
  navigator.clipboard.writeText(content)
    .then(() => ElMessage.success('复制成功'))
    .catch(() => ElMessage.error('复制失败'))
}

// 编辑相关方法
const handleEdit = () => {
  editInfo.value = { ...viewInfo.value }
  isEditing.value = true
}

const cancelEdit = () => {
  isEditing.value = false
}

const saveEdit = () => {
  if (!editInfo.value.name || !editInfo.value.description) {
    ElMessage.warning('请填写完整信息')
    return
  }

  const listRef = viewDialogType.value === 'my' ? myInfoList : targetInfoList
  const cookieKey = viewDialogType.value === 'my' ? 'myInfoList' : 'targetInfoList'
  const currentInfo = viewDialogType.value === 'my' ? 'myInfo' : 'targetInfo'

  // 更新列表中的信息
  const index = listRef.value.findIndex(item => item.name === viewInfo.value.name)
  if (index !== -1) {
    listRef.value[index] = { ...editInfo.value }
    Cookies.set(cookieKey, JSON.stringify(listRef.value))
    
    // 如果正在编辑的是当前选中的信息，也需要更新
    const selectedInfo = Cookies.get(currentInfo)
    if (selectedInfo) {
      const selected = JSON.parse(selectedInfo)
      if (selected.name === viewInfo.value.name) {
        Cookies.set(currentInfo, JSON.stringify(editInfo.value))
      }
    }
  }

  viewInfo.value = { ...editInfo.value }
  isEditing.value = false
  ElMessage.success('修改成功')
}

// 删除信息
const handleDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这条信息吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    const listRef = viewDialogType.value === 'my' ? myInfoList : targetInfoList
    const cookieKey = viewDialogType.value === 'my' ? 'myInfoList' : 'targetInfoList'
    const currentInfo = viewDialogType.value === 'my' ? 'myInfo' : 'targetInfo'

    // 从列表中删除
    const index = listRef.value.findIndex(item => item.name === viewInfo.value.name)
    if (index !== -1) {
      listRef.value.splice(index, 1)
      Cookies.set(cookieKey, JSON.stringify(listRef.value))

      // 如果删除的是当前选中的信息，需要清除选中状态
      const selectedInfo = Cookies.get(currentInfo)
      if (selectedInfo) {
        const selected = JSON.parse(selectedInfo)
        if (selected.name === viewInfo.value.name) {
          Cookies.remove(currentInfo)
        }
      }
    }

    viewDialogVisible.value = false
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 生命周期钩子
onMounted(() => {
  // 从 Cookie 中加载数据
  const savedMyInfoList = Cookies.get('myInfoList')
  const savedTargetInfoList = Cookies.get('targetInfoList')
  
  if (savedMyInfoList) {
    myInfoList.value = JSON.parse(savedMyInfoList)
  }
  if (savedTargetInfoList) {
    targetInfoList.value = JSON.parse(savedTargetInfoList)
  }

  // 默认选择找话题风格
  selectedStyle.value = 'topic'
})
</script>

<style scoped>
.inter-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  background: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.back-button {
  cursor: pointer;
  padding: 8px;
}

.search-box {
  flex: 1;
}

.notice-bar {
  margin-bottom: 20px;
}

.style-section {
  background: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.style-title {
  margin-bottom: 15px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 10px;
}

.style-options {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
  gap: 10px;
}

.style-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #e4e7ed;
}

.style-item.active {
  background: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

.style-item .emoji {
  font-size: 24px;
  margin-bottom: 5px;
}

.style-item .label {
  font-size: 14px;
}

.role-selection {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.role-item {
  flex: 1;
}

.search-results {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.results-title {
  font-weight: bold;
  color: #303133;
}

.response-time {
  color: #909399;
  font-size: 14px;
}

.loading-container {
  padding: 20px 0;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.result-item:hover {
  background: #f5f7fa;
}

.result-content {
  flex: 1;
  margin-right: 15px;
  line-height: 1.5;
}

.custom-dialog {
  border-radius: 8px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-button) {
  border-radius: 8px;
}

.info-view {
  padding: 20px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.info-item .label {
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.info-item .value {
  flex: 1;
  color: #303133;
}

.gender-tag {
  margin-left: 8px;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-icon) {
  margin-right: 5px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 0;
}

.dialog-header h4 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.dialog-actions {
  display: flex;
  gap: 8px;
}

.edit-form {
  padding: 20px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding-right: 20px;
}
</style>
